﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;

namespace RStein.Posterous.API
{    
    
    internal class SimpleDownloader : ISimpleDownloader
    {

        #region methods
        protected virtual void OnWebRequestCreated(EventArgsValue<WebRequest> e)
        {
            EventHandler<EventArgsValue<WebRequest>> handler = WebRequestCreated;
            if (handler != null)
            {
                handler(this, e);
            }
        }

        protected virtual void OnWebResponseCreated(EventArgsValue<WebResponse> e)
        {
            EventHandler<EventArgsValue<WebResponse>> handler = WebResponseCreated;
            if (handler != null)
            {
                handler(this, e);
            }
        }

        #endregion methods
        
        public virtual Stream DownloadFile(string fileUrl)
        {
            var client = SimpleWebFactory.Instance.Create<IWebClient>();

            client.SetWebClientActions(
                                        req => OnWebRequestCreated(new EventArgsValue<WebRequest>(req, null)),
                                        resp => OnWebResponseCreated(new EventArgsValue<WebResponse>(resp, null)));
                                
            using (client as IDisposable)
                   
            {
                try
                {
                    byte[] file = client.DownloadData(fileUrl);
                    var fileStream = new MemoryStream(file);
                    fileStream.Position = 0;
                    return fileStream;
                }
                catch (Exception e)
                {                    
                    Debug.WriteLine(e);
                    var ex = new PosterousException(GlobalConstants.INVALID_RESPONSE_EX, e);
                    throw ex;
                }
                

            }
        }

        #region IRawRequestResponsePublisher Members

        public event EventHandler<EventArgsValue<WebRequest>> WebRequestCreated;

        
        public event EventHandler<EventArgsValue<WebResponse>> WebResponseCreated;
        
        #endregion

        #region Implementation of IExtensionInterface

        public T GetInterface<T>() where T : class
        {
            return this as T;
        }

        #endregion
    }

    
}
